<?php

/**
 * 文件相关控制器
 */

namespace app\common\file;

use app\BaseController;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;

class ExcelService extends BaseController
{
    /**
     * 导入excel
     *
     * @return void
     */
    public static function importExcel()
    {
        set_time_limit(0);
        //文件上传导入
        // $fileController=new FileController();
        $res = self::uploadFileImport();
        if ($res) {
            //修正路径
            $filename = app()->getRootPath() . '/public/storage/' . str_replace('\\', '/', $res);
            //进行读取
            $spreadsheet = IOFactory::load($filename);
            $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
            array_shift($sheetData);  //删除标题;
            array_shift($sheetData);  //删除标题;
            return ['data' => $sheetData, 'path' => '/' . str_replace('\\', '/', $res)];
        } else {
            return '';
        }
    }

    //文件上传,导入文件专用,数据不入库
    public static function uploadFileImport()
    {
        // 获取表单上传文件
        $file = \request()->file('file');
        // 移动到框架应用根目录/public/storage/ 目录下
        if ($file) {
            $savename = \think\facade\Filesystem::disk('public')->putFile('importExcel', $file);
            return $savename;
        }
        error('上传失败');
    }

    public static function exportExcel($filename, $data, $type)
    {
        $newExcel = new Spreadsheet();  //创建一个新的excel文档
        $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
        //设置宽度为true,不然太窄了
        $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        if ($type == 1) {
            $objSheet->setTitle('工时表');  //设置当前sheet的标题
            //设置第一栏的标题
            $objSheet->setCellValue('A1', 'id')
                ->setCellValue('B1', '姓名')
                ->setCellValue('C1', '身份证号')
                ->setCellValue('D1', '服务单位')
                ->setCellValue('E1', '工时/h');
            foreach ($data as $k => $val) {
                $k = $k + 2;
                $objSheet->setCellValue('A' . $k, $val['id'])
                    ->setCellValue('B' . $k, $val['name'])
                    ->setCellValue('C' . $k, $val['id_num'])
                    ->setCellValue('D' . $k, $val['service_unit'])
                    ->setCellValue('E' . $k, $val['work_hour']);
            }
        } elseif ($type == 2) {
            $objSheet->setTitle('在职人员表');  //设置当前sheet的标题
            //设置第一栏的标题
            $objSheet->setCellValue('A1', 'id')
                ->setCellValue('B1', '姓名')
                ->setCellValue('C1', '身份证号')
                ->setCellValue('D1', '入职时间')
                ->setCellValue('E1', '工作地点')
                ->setCellValue('F1', '服务单位');
            foreach ($data as $k => $val) {
                $k = $k + 2;
                $objSheet->setCellValue('A' . $k, $val['id'])
                    ->setCellValue('B' . $k, $val['name'])
                    ->setCellValue('C' . $k, $val['id_num'])
                    ->setCellValue('D' . $k, date('Y-m-d', strtotime($val['entry_time'])))
                    ->setCellValue('E' . $k, $val['address_sheng'].$val['address_shi'].$val['address_details'])
                    ->setCellValue('F' . $k, $val['company_name']);
            }    
        } elseif ($type == 3) {
            $objSheet->setTitle('离职人员表');  //设置当前sheet的标题
            //设置第一栏的标题
            $objSheet->setCellValue('A1', 'id')
                ->setCellValue('B1', '姓名')
                ->setCellValue('C1', '身份证号')
                ->setCellValue('D1', '联系电话')
                ->setCellValue('E1', '离职时间')
                ->setCellValue('F1', '离职原因');
            foreach ($data as $k => $val) {
                $k = $k + 2;
                $objSheet->setCellValue('A' . $k, $val['id'])
                    ->setCellValue('B' . $k, $val['name'])
                    ->setCellValue('C' . $k, $val['id_num'])
                    ->setCellValue('D' . $k, $val['phone'])
                    ->setCellValue('E' . $k, date('Y-m-d', strtotime($val['leave_time'])))
                    ->setCellValue('F' . $k, $val['cause']);
            }
        } elseif ($type == 4) {
            $objSheet->setTitle('待职人员表');  //设置当前sheet的标题
            //设置第一栏的标题
            $objSheet->setCellValue('A1', 'id')
                ->setCellValue('B1', '姓名')
                ->setCellValue('C1', '性别')
                ->setCellValue('D1', '年龄')
                ->setCellValue('E1', '身份证号')
                ->setCellValue('F1', '联系电话')
                ->setCellValue('G1', '登记时间')
                ->setCellValue('H1', '期望岗位')
                ->setCellValue('I1', '曾经工作岗位')
                ->setCellValue('J1', '期望薪资 元/月')
                ->setCellValue('K1', '有无病史');
            foreach ($data as $k => $val) {
                $k = $k + 2;
                $expect_work_name = '';
                if (!empty($val['expect_work_name'])) {
                    foreach ($val['expect_work_name'] as $kk => $vv) {
                        $expect_work_name .= $vv.',';
                    }
                }
                $objSheet->setCellValue('A' . $k, $val['id'])
                    ->setCellValue('B' . $k, $val['name'])
                    ->setCellValue('C' . $k, $val['sex'] == 1 ? '男' : '女')
                    ->setCellValue('D' . $k, $val['age'])
                    ->setCellValue('E' . $k, $val['id_num'])
                    ->setCellValue('F' . $k, $val['phone'])
                    ->setCellValue('G' . $k, date('Y-m-d', strtotime($val['create_time'])))
                    ->setCellValue('H' . $k, $expect_work_name)
                    ->setCellValue('I' . $k, $val['before_work'])
                    ->setCellValue('J' . $k, $val['compensation'])
                    ->setCellValue('K' . $k, $val['is_ill'] = 1 ? '有' : '无');
            }
        } else {
            error('参数错误');
        }
        self::downloadExcel($newExcel, $filename, 'Xls');
        return $filename . '.Xls';
    }
    //公共文件，用来传入xls并下载
    public static function downloadExcel($newExcel, $filename, $format)
    {
        ob_end_clean();
        // $format只能为 Xlsx 或 Xls
        if ($format == 'Xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        } elseif ($format == 'Xls') {
            header('Content-Type: application/vnd.ms-excel');
        }

        header("Content-Disposition: attachment;filename="
            . $filename . date('Y-m-d') . '.' . strtolower($format));
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($newExcel, $format);

        // $objWriter->save('php://output');

        //通过php保存在本地的时候需要用到
        $path = public_path() . 'storage\exportExcel\\' . $filename . '.' . $format;
        $objWriter->save($path);
        return $path;
        //以下为需要用到IE时候设置
        // If you're serving to IE 9, then the following may be needed
        // header('Cache-Control: max-age=1');
        // //         If you're serving to IE over SSL, then the following may be needed
        // header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        // header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        // header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        // header('Pragma: public'); // HTTP/1.0
        exit;
    }
}
